from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import F
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from commodity.models import Types, CommodityInfo


# Create your views here.

def commodityView(request):
    """
    商品列表视图
    - 支持分类，排序，搜索
    - 实现分页
    """
    title = '商品列表'
    # 页面分类标识
    # classContent = 'commoditys'
    classContent = 'commodity-content'

    firsts = Types.objects.values('firsts').distinct()
    typesList = Types.objects.all()
    # 首先查询Type的字段id等于t的数据A
    # 然后从数据A中获取字段seconds的数据B
    t = request.GET.get('t', '')
    # s设置排列方式，为空默认s=sold，sold代表数据库的字段
    s = request.GET.get('s', 'sold')
    # p设置页数，默认1
    p = request.GET.get('p', '1')
    # n商品搜索功能的关键字，进行模糊匹配
    # 查询条件name_contains=n
    n = request.GET.get('n', '')

    # 初始化商品查询集
    commodityInfos = CommodityInfo.objects.all()
    # for commodityInfo in commodityInfos:
    #     print(commodityInfo.name)
    if t:
        # 根据id筛选
        types = Types.objects.filter(id=t).first()
        commodityInfos =commodityInfos.filter(types=types.seconds)
    if s:
        # 根据指定字段排序
        commodityInfos =commodityInfos.order_by('-' + s)
    if n:
        # 模糊搜索
        commodityInfos =commodityInfos.filter(name__contains=n)

    # 分页处理
    # 每页6条,p不是整数,那么默认返回1
    # p大于总页数,默认返回最后一个商品信息
    paginator = Paginator(commodityInfos, 6)
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        # 超出范围
        pages = paginator.page(paginator.num_pages)

    return render(request, 'commodity.html', locals())

def detailView(request, id):
    """
    商品详情页面
    """
    title = '商品介绍'
    # classContent = 'details'
    classContent = 'datails-content'
    # 查询前五个
    items = CommodityInfo.objects.exclude(id=id).order_by('-sold')[:5]
    # 查询ID，没有就返回None
    commodity = CommodityInfo.objects.filter(id=id).first()
    # 从session获取用户收藏列表
    likesList = request.session.get('likes', [])
    # 判断当前商品是否被用户收藏
    likes = True if id in likesList else False

    return render(request, 'details.html', locals())

def collectView(request):
    """
    商品收藏视图函数(AJAX接口)
    - 收藏请求，收藏数量
    - Session，Cookie
    """
    # 代表当前商品的主键
    id = request.GET.get('id', '')
    # 响应内容
    result = {"result":"已收藏"}
    # 从请求对象request获取session数据
    # 处理likes
    likes = request.session.get('likes', [])
    if id and not int(id) in likes:
        CommodityInfo.objects.filter(id=id).update(likes=F('likes') + 1)
        # 更改响应内容
        result["result"] = "收藏成功"
        request.session['likes'] = likes + [int(id)]
    # 返回json响应
    # JsonResponse将字典转换为json数据
    return JsonResponse(result)
